﻿using QWManage.API.AccessToken;
using QWManage.API.TagMgr92118;
using QWManage.DAL;
using QWManage.Forms;
using QWManage.Model;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace QWManage
{
    public partial class FrmSearch : Form
    {
        private Thread _thread;
        private HashSet<string> _hashset_avatar_blocked;
        public HashSet<string> _hashset_userid_ingroups;
        public FrmSearch()
        {
            InitializeComponent();
            this.FormClosing += (s, e) =>
            {
                if (_thread != null && _thread.IsAlive) _thread.Abort();
            };
        }

        private void FrmSearch_Load(object sender, EventArgs e)
        {
            _hashset_avatar_blocked = new BlockedDAL().GetAvatarHashSet();
            _hashset_userid_ingroups = new CustomersGroupsDAL().GetMemberInGroupHashSet();

            cmbInGroup.Items.Clear();
            cmbInGroup.Items.Add("全部");
            cmbInGroup.Items.Add("在群");
            cmbInGroup.Items.Add("不在群");
            cmbInGroup.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbInGroup.SelectedIndex = 0;

            cmbBlocked.Items.Clear();
            cmbBlocked.Items.Add("全部");
            cmbBlocked.Items.Add("在黑名单");
            cmbBlocked.Items.Add("不在黑名单");
            cmbBlocked.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbBlocked.SelectedIndex = 0;


            lvCustomers.View = View.Details;
            lvCustomers.Items.Clear();
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "Name", Text = "Name", Width = 200 });
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "ID", Text = "ID", Width = 260 });
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "Type", Text = "Type", Width = 50 });
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "Unionid", Text = "Unionid", Width = 200 });
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "Avatar", Text = "Avatar", Width = 300 });

            lvCustomers.Columns.Add(new ColumnHeader() { Name = "F_UserID", Text = "UserID", Width = 100 });
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "F_Rmeark", Text = "Rmeark", Width = 100 });

            lvCustomers.Columns.Add(new ColumnHeader() { Name = "F_Desrciption", Text = "Desrciption", Width = 100 });
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "F_CreateTime", Text = "CreateTime", Width = 100 });
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "F_Add_Way", Text = "Add_Way", Width = 100 });

            lvCustomers.Columns.Add(new ColumnHeader() { Name = "F_Oper_UserID", Text = "Oper_UserID", Width = 100 });
            lvCustomers.Columns.Add(new ColumnHeader() { Name = "F_Tag_IDS", Text = "Tag_IDS", Width = 100 });



            lvCustomers.CheckBoxes = true;
            lvCustomers.FullRowSelect = true;
            lvCustomers.MultiSelect = true;

            initializeDataService();


            //_thread = new Thread(new ThreadStart(initializeDataService));
            //_thread.Start();
        }


        private void setDepartments()
        {
            DepartmentInfo department = _departmentDAL.GetSubDepartments(0)[0];
            btnDepartments.Text = "选择部门";
            btnDepartments.Tag = department;
            foreach (var departmentInfo in _departmentDAL.GetSubDepartments(department.ID))
            {
                ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem();
                toolStripMenuItem.Text = departmentInfo.Name;
                toolStripMenuItem.Tag = departmentInfo;
                toolStripMenuItem.Click += ToolStripMenuItem_Click;
                btnDepartments.DropDownItems.Add(toolStripMenuItem);
                setSubToolStripMenuItem(toolStripMenuItem);
            }
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DepartmentInfo department = (DepartmentInfo)(sender as ToolStripMenuItem).Tag;
            setUsers(department.ID);
            btnDepartments.Text = department.Name;
        }

        DepartmentDAL _departmentDAL = new DepartmentDAL();
        private void setSubToolStripMenuItem(ToolStripMenuItem toolStripMenuItem)
        {
            DepartmentInfo department = toolStripMenuItem.Tag as DepartmentInfo;
            foreach (var departmentInfo in _departmentDAL.GetSubDepartments(department.ID))
            {
                ToolStripMenuItem subMenuItem = new ToolStripMenuItem();
                subMenuItem.Text = departmentInfo.Name;
                subMenuItem.Tag = departmentInfo;
                subMenuItem.Click += ToolStripMenuItem_Click;
                toolStripMenuItem.DropDownItems.Add(subMenuItem);
                setSubToolStripMenuItem(subMenuItem);
            }
        }

        private void setUsers(int? departmentid = null)
        {
            cmbUsers.ComboBox.DataSource = null;
            UsersDepartmentsRDAL usersDepartmentsRDAL = new UsersDepartmentsRDAL();
            UserDAL userDAL = new UserDAL();
            List<UserInfo> users_all = userDAL.GetUserInfos();
            List<UserInfo> users = new List<UserInfo>();
            if (departmentid != null)
            {
                List<string> userids = usersDepartmentsRDAL.GetUserIds(departmentid.Value);
                foreach (UserInfo user in users_all)
                {
                    if (userids.Contains(user.UserID))
                        users.Add(user);
                }
                cmbUsers.DropDownStyle = ComboBoxStyle.DropDownList;
                cmbUsers.ComboBox.DataSource = users;
                cmbUsers.ComboBox.DisplayMember = "Name";
                cmbUsers.ComboBox.ValueMember = "UserID";
            }
        }

        private void initializeDataService()
        {
            try
            {
                lblStatus.Text = "数据初始化中....";
                this.Cursor = Cursors.WaitCursor;
                foreach (Control control in this.Controls) { control.Enabled = false; }

                setDepartments();
                setUsers();

                string tokenA = TokenA.GetAccessToken();
                API.TagLibrary92117.TagLibraryArgs tagLibraryArgs = new API.TagLibrary92117.TagLibraryArgs();
                tagLibraryArgs.group_id = null;
                tagLibraryArgs.tag_id = null;
                List<TagInfo> tags = API.TagLibrary92117.TagLibraryAPI.Invoke(tokenA, tagLibraryArgs);

                cmbTags.Items.Clear();
                cmbTags.DropDownStyle = ComboBoxStyle.DropDownList;
                cmbTags.ComboBox.DataSource = tags;
                cmbTags.ComboBox.DisplayMember = "Name";
                cmbTags.ComboBox.ValueMember = "ID";

                lblStatus.Text = $"共 {lvCustomers.Items.Count} 条记录";
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                foreach (Control control in this.Controls) { control.Enabled = true; }
            }
        }

        private static List<DepartmentInfo> getSubDepartments(int id)
        {
            DepartmentDAL departmentDAL = new DepartmentDAL();
            List<DepartmentInfo> departmentInfos = departmentDAL.GetSubDepartments(id);
            foreach (DepartmentInfo departmentInfo in departmentInfos)
            {
                departmentInfo.SubDepartments = getSubDepartments(departmentInfo.ID);
            }
            return departmentInfos;
        }

        private void btnChooseAll_Click(object sender, EventArgs e)
        {
            _thread = new Thread(new ThreadStart(chooseAllService));
            _thread.Start();
        }

        private void chooseAllService()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        foreach (Control control in this.Controls) { control.Enabled = false; }
                        this.Cursor = Cursors.WaitCursor;
                        foreach (ListViewItem item in lvCustomers.Items) { item.Checked = true; }
                    }));
                }
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.Cursor = Cursors.Default;
                        foreach (Control control in this.Controls) { control.Enabled = true; }
                    }));
                }
            }
        }
        private void chooseNoneService()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        foreach (Control control in this.Controls) { control.Enabled = false; }
                        this.Cursor = Cursors.WaitCursor;
                        foreach (ListViewItem item in lvCustomers.Items) { item.Checked = false; }
                    }));
                }

            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.Cursor = Cursors.Default;
                        foreach (Control control in this.Controls) { control.Enabled = true; }
                    }));
                }
            }
        }

        private void btnChooseNone_Click(object sender, EventArgs e)
        {
            _thread = new Thread(new ThreadStart(chooseNoneService));
            _thread.Start();
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            int count = lvCustomers.CheckedItems.Count;
            TagInfo tag = cmbTags.ComboBox.SelectedItem as TagInfo;
            if (count == 0)
            {
                MessageBox.Show("未选中任何用户，请先选择用户", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var result = MessageBox.Show($"确定要为 {count} 位用户添加标签\"{tag.Name}\"", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result != DialogResult.Yes) return;

            _thread = new Thread(new ThreadStart(editTagService));
            _thread.Start();
        }

        private void editTagService()
        {
            try
            {
                lblStatus.Text = "标签修改中....";
                this.Cursor = Cursors.WaitCursor;
                foreach (Control control in this.Controls) { control.Enabled = false; }

                UserInfo userInfo = cmbUsers.ComboBox.SelectedItem as UserInfo;
                TagInfo tag = cmbTags.ComboBox.SelectedItem as TagInfo;
                string tokenA = API.AccessToken.TokenA.GetAccessToken();
                int success = 0;
                int failure = 0;
                progressBar.Value = 0;
                progressBar.Minimum = 0;
                progressBar.Maximum = lvCustomers.CheckedItems.Count;
                foreach (ListViewItem item in lvCustomers.CheckedItems)
                {
                    CustomerInfo customer = item.Tag as CustomerInfo;
                    //编辑客户企业标签
                    TagMgrArgs makeTagArgs = new TagMgrArgs();
                    makeTagArgs.userid = userInfo.UserID;
                    makeTagArgs.external_userid = customer.Exuserid;
                    //删除标签
                    //et2rMqDAAAoVZL3EYPAahbZBDfisCT4Q,一般
                    makeTagArgs.remove_tag = new string[] { };
                    //添加标签
                    //et2rMqDAAAR0p2uYl - XW2QAIPJ_14duA,重要
                    //et2rMqDAAAmwnBBfie5ICmFwswV5Z3VA, 核心
                    makeTagArgs.add_tag = new string[] { tag.ID };
                    bool result = TagMgrAPI.Invoke(tokenA, makeTagArgs);
                    success += result ? 1 : 0;
                    failure += result ? 0 : 1;
                    progressBar.Value += 1;
                }
                MessageBox.Show($"操作完成，成功 {success} 条，失败 {failure} 条", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                progressBar.Value = 0;
                foreach (Control control in this.Controls) { control.Enabled = true; }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (cmbUsers.Items.Count == 0)
            {
                MessageBox.Show("请先选择用户", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            _thread = new Thread(new ThreadStart(searchService));
            _thread.Start();
        }

        private void searchService()
        {
            try
            {
                lblStatus.Text = "数据查询中....";


                List<TagInfo> tagInfos = cmbTags.ComboBox.DataSource as List<TagInfo>;
                Dictionary<string, string> tagIDNameDic = new Dictionary<string, string>();
                if (tagInfos != null)
                {
                    foreach (TagInfo tagInfo in tagInfos)
                    {
                        if (!tagIDNameDic.ContainsKey(tagInfo.ID))
                            tagIDNameDic.Add(tagInfo.ID, tagInfo.Name);
                    }
                }
                this.Cursor = Cursors.WaitCursor;
                foreach (Control control in this.Controls) { control.Enabled = false; }

                DateConfigInfo dateConfigInfo = DateConfigMgr.Get();
                int start_dt = dateConfigInfo.Start;
                int end_dt = dateConfigInfo.End;
                ExtagsConfigInfo extagsConfigInfo = ExtagsConfigMgr.Get();


                UserInfo userInfo = cmbUsers.ComboBox.SelectedItem as UserInfo;
                CustomerDAL customerDAL = new CustomerDAL();
                List<string> exuserids = customerDAL.GetExuserIDs(userInfo.UserID);
                List<CustomerInfo> customerInfos = customerDAL.GetCustomerInfos(exuserids);
                lvCustomers.Items.Clear();
                progressBar.Value = 0;
                progressBar.Minimum = 0;
                progressBar.Maximum = customerInfos.Count;
                List<ListViewItem> list = new List<ListViewItem>();
                foreach (CustomerInfo customerInfo in customerInfos)
                {
                    progressBar.Value += 1;

                    if (customerInfo.F_CreateTime > end_dt || customerInfo.F_CreateTime < start_dt) continue;
                    if (!string.IsNullOrEmpty(customerInfo.F_Tag_IDS))
                    {
                        string[] tagids = customerInfo.F_Tag_IDS.Split('\t');
                        bool matched = false;
                        foreach (string tagid in tagids)
                        {
                            if (extagsConfigInfo.TagIds.Contains(tagid.TrimEnd('\t').Trim()))
                            {
                                matched = true;
                                break;
                            }
                        }
                        if (matched) continue;
                    }

                    //保留在黑名单中的
                    if (cmbBlocked.ComboBox.SelectedIndex == 1)
                    {
                        if (!_hashset_avatar_blocked.Contains(customerInfo.Avatar)) continue;
                    }
                    //保留不在黑名单中的
                    else if (cmbBlocked.ComboBox.SelectedIndex == 2)
                    {
                        if (_hashset_avatar_blocked.Contains(customerInfo.Avatar)) continue;
                    }

                    //保留在群中的
                    if (cmbInGroup.ComboBox.SelectedIndex == 1)
                    {
                        if (!_hashset_userid_ingroups.Contains(customerInfo.Exuserid)) continue;
                    }
                    //保留不在群中的
                    else if (cmbInGroup.ComboBox.SelectedIndex == 2)
                    {
                        if (_hashset_userid_ingroups.Contains(customerInfo.Exuserid)) continue;
                    }



                    ListViewItem lvItem = new ListViewItem(customerInfo.Name);
                    lvItem.SubItems.Add(customerInfo.Exuserid);
                    lvItem.SubItems.Add(customerInfo.Type.HasValue ? customerInfo.Type.ToString() : "");
                    lvItem.SubItems.Add(customerInfo.Unionid != null ? customerInfo.Unionid : "");
                    lvItem.SubItems.Add(customerInfo.Avatar != null ? customerInfo.Avatar : "");

                    lvItem.SubItems.Add(customerInfo.F_UserID != null ? customerInfo.F_UserID : "");
                    lvItem.SubItems.Add(customerInfo.F_Rmeark != null ? customerInfo.F_Rmeark : "");
                    lvItem.SubItems.Add(customerInfo.F_Desrciption != null ? customerInfo.F_Desrciption : "");

                    if (customerInfo.F_CreateTime.HasValue)
                    {
                        DateTimeOffset dateTime = DateTimeOffset.FromUnixTimeSeconds(customerInfo.F_CreateTime.Value);
                        lvItem.SubItems.Add(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    else
                    {
                        lvItem.SubItems.Add("");
                    }

                    lvItem.SubItems.Add(customerInfo.F_Add_Way.ToString());
                    lvItem.SubItems.Add(customerInfo.F_Oper_UserID != null ? customerInfo.F_Oper_UserID : "");

                    if (customerInfo.F_Tag_IDS != null)
                    {
                        string[] arr = customerInfo.F_Tag_IDS.Split('\t');
                        string tags = " ";
                        foreach (string str in arr)
                        {
                            string key = str.TrimEnd('\t').TrimEnd();
                            if (tagIDNameDic.ContainsKey(key))
                            {
                                tags += tagIDNameDic[key] + " ";
                            }
                            else tags += str + " ";
                        }
                        lvItem.SubItems.Add(tags.Trim());
                    }
                    else
                        lvItem.SubItems.Add("");
                    lvItem.Tag = customerInfo;
                    list.Add(lvItem);
                }
                lvCustomers.Items.AddRange(list.ToArray());

                lblStatus.Text = $"共 {Utils.Common.FormatInt32(lvCustomers.Items.Count)} 条记录";
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                progressBar.Value = 0;
                foreach (Control control in this.Controls) { control.Enabled = true; }
            }
        }

        private void btnChoose50_Click(object sender, EventArgs e)
        {
            _thread = new Thread(new ThreadStart(choose50Service));
            _thread.Start();
        }

        private void choose50Service()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        foreach (Control control in this.Controls) { control.Enabled = false; }
                        this.Cursor = Cursors.WaitCursor;
                        int count = 0;
                        foreach (ListViewItem item in lvCustomers.Items)
                        {
                            item.Checked = true;
                            count++;
                            if (count == 50) break;
                        }
                    }));
                }
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.Cursor = Cursors.Default;
                        foreach (Control control in this.Controls) { control.Enabled = true; }
                    }));
                }
            }
        }

        private void btnTags_Click(object sender, EventArgs e)
        {
            FrmExtags frm = new FrmExtags();
            if (frm.ShowDialog() != DialogResult.OK)
            {

            }
        }

        private void btnDateTime_Click(object sender, EventArgs e)
        {
            FrmDate frm = new FrmDate();
            if (frm.ShowDialog() == DialogResult.OK)
            {

            }
        }
    }
}
